package com.diaohw.platform.framework.authorization;

import cn.dev33.satoken.stp.StpInterface;
import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component
public class AuthorizationInterface implements StpInterface {

    private final static String ROLE_KEY = "ROLE:";
    private final static String PERMISSION_KEY = "PERMISSION:";

    /**
     * 标记：是否已初始化成功
     */
    @Autowired
    @Qualifier("aloneRedisTemplate")
    private StringRedisTemplate template;

    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        Set<String> members = template.opsForSet().members(key(loginId, loginType, PERMISSION_KEY));
        if (members == null) {
            return List.of();
        }
        return new ArrayList<>(members);
    }

    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        Set<String> members = template.opsForSet().members(key(loginId, loginType, ROLE_KEY));
        if (members == null) {
            return List.of();
        }
        return new ArrayList<>(members);
    }

    /**
     * 存储用户权限CODE
     *
     * @param loginId        登录用户ID
     * @param loginType      登录类型
     * @param permissionList 权限CODE
     */
    public void setPermissionList(Object loginId, String loginType, List<String> permissionList) {
        setValue(PERMISSION_KEY, loginId, loginType, permissionList);

    }

    /**
     * 存储登录用户角色
     *
     * @param loginId   登录用户ID
     * @param loginType 登录类型
     * @param roleList  角色CODE
     */
    public void setRoleList(Object loginId, String loginType, List<String> roleList) {
        setValue(ROLE_KEY, loginId, loginType, roleList);

    }

    /**
     * 存储
     *
     * @param prefix    Redis key 前缀
     * @param loginId   登录用户ID
     * @param loginType 登录类型
     * @param values    CODE值
     */
    private void setValue(String prefix, Object loginId, String loginType, List<String> values) {
        if (values == null || values.isEmpty()) {
            return;
        }
        String[] array = values.toArray(new String[0]);
        String key = key(loginId, loginType, prefix);
        template.opsForSet().add(key, array);
        template.expire(key, Duration.ofDays(7));
    }

    /**
     * 拼接Redis key
     *
     * @param loginId   登录用户ID
     * @param loginType 登录类型
     * @param prefix    Redis key 前缀
     * @return {@code prefix:loginType:loginId}
     */
    private String key(Object loginId, String loginType, String prefix) {
        if (StrUtil.isBlank(loginType)) {
            return prefix + "login:" + loginId;
        }
        return prefix + loginType + ":" + loginId;
    }
}
